20180505做一個AMG評價的實際應用吧
今天我們試試看用爬蟲挑出All Music網站,Acid Jazz這個音樂類別裏頭5顆星的專輯,
因為selenium是無法做post的,(果然實際練習就會遇到很多問題啊)
所以這次我們需要使用到selenium-requests這個模組 (pip3 install selenium-requests)。
https://pypi.org/project/selenium-requests/
首先我們將上一次取得AMG label的代碼,
改成seleniumre-quests的方法,實際上大小意如下:
from seleniumrequests import Chrome #導入模組
chrome_path = r"C:\Users\Ramone\seleniumdriver\chrome\chromedriver.exe" # 給定一個瀏覽器的local位置
webdriver = Chrome(chrome_path) # 導入Chorme當作webdriver
label_res= webdriver.request('GET','https://www.allmusic.com/advanced-search/') # 輸入網址,用GET方法取得原始碼
#print (label_res.text)
#篩出原始碼裡的類別並建立python字典
import requests
import re
from bs4 import BeautifulSoup
label_soup = BeautifulSoup(label_res.text,"lxml")
label = label_soup.find_all('input',{'id':re.compile('genreid.*?')})
label_dict={}
for l in label:
label_dict[l['value']]=l['id']
#print (l['value'],l['id'])
用開發人員工具我們可以發現
AMG網頁是用POST向 https://www.allmusic.com/advanced-search/results/,這個網址提出請求。
所以接下來我們需要以下兩個資訊,(皆可以從開發人員工具network取得)
1.Request Headers (不確定為什麼一定要,待學習:Http headers)
2.Form data (這裡需要用到AMG label的id)
#headers直接從network複製
amg_header={
'accept': r'text/html, */*; q=0.01',
'accept-encoding': r'gzip, deflate, br',
'accept-language': r'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6',
'content-length': '39',
'content-type': r'application/x-www-form-urlencoded; charset=UTF-8',
'cookie': r'_ga=GA1.2.85029673.1513518205; __gads=ID=3275e8321c618a22:T=1513518176:S=ALNI_MbT7eOHrtfYxgOBlXi-4NZzwkA01Q; __qca=P0-704611526-1513518207321; policy=notified; registration_prompt=true; _gid=GA1.2.939754473.1525263314; bm_monthly_unique=true; allmusic_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22498c8bf394d58ea40993a276a34e6bfc%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A11%3A%2210.128.8.22%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A115%3A%22Mozilla%2F5.0+%28Windows+NT+10.0%3B+Win64%3B+x64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F65.0.3325.181+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1525278399%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22user%22%3Bi%3A0%3B%7Dedeeacbf1b0d945d29d143bc59a40129; _gat=1; _gat_cToolbarTracker=1; bm_last_load_status=BLOCKING; bm_daily_unique=true; bm_sample_frequency=100',
'origin': r'https://www.allmusic.com',
'referer': r'https://www.allmusic.com/advanced-search',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
'x-requested-with': 'XMLHttpRequest',
}
#formdata
amg_label=label_dict['Acid Jazz'] #id我們從字典裡呼叫出來
amg_rating='editorialrating:9' #rating則直接給定值五顆星
接下來就是給我們的header和data使用POST的方法取得原始碼。
檢查完請求的原始碼之後一樣丟給BS剖析。
res= webdriver.request('POST','https://www.allmusic.com/advanced-search/results/'
,headers=amg_header,data="filters[]=%s&filters[]=%s" %(label_dict[label_input],amg_rating))
#print (res.text)
#用開發人員工具,找原始碼內的規則丟給BS做剖析
res_soup = BeautifulSoup(res.text,'lxml')
artist = res_soup.find_all('td',{'class':'artist'})
year = res_soup.find_all('td',{'class':'year'})
album = res_soup.find_all('td',{'class':'title'})
#建立空list給之後迴圈加入
artist_list=[]
year_list=[]
album_list=[]
#因為子標籤的關係,跑出來會有不少換行符號,我們用strip這個方法把它濾掉。
for t in album:
t_text=t.text
t_str=t_text.strip()
album_list.append(t_str)
for a in artist:
a_text=a.text
a_str=a_text.strip()
artist_list.append(a_str)
for y in year:
y_text=y.text
y_str=y_text.strip()
year_list.append(y_str)
i=0
while i < len(album_list):
print (artist_list[i],'-',album_list[i],'-',year_list[i])
i=i+1
###Output
#Squarepusher - Hard Normal Daddy - 1997
因為範例只有一頁的資料,所以不需要做其他頁的post,
此次的代碼只能取得一頁的資料,
剩下換頁的post,帶有時間在將它完善。
本次的練習在headers和整理子標籤問題卡關了很久,
目前在做POST爬蟲時,仍不確定何時需要headers,
子標籤的換行問題,先用土炮的strip方法解決的,
但看起來bs是有機會直接抓出子標籤的,這個也要花時間學習。
https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/